<template>

  <uv-navbar title="" placeholder bgColor="transparent" leftIcon="" :autoBack="false">
    <template #left>
      首页
    </template>
  </uv-navbar>
  <view>
    <!-- top_banner_swiper -->
    <view class="banner-container">
      <swiper :autoplay="autoplay" :interval="interval" :duration="duration">
        <swiper-item>
          <view class="top_banner">
            <view class="top_banner_title">{{ customerLoginInfo.companyName }}</view>
            <view class="top_banner_dec">您的服务商</view>
            <view class="top_banner_tel" @tap="callPhone">拨打电话</view>
          </view>
        </swiper-item>
      </swiper>
      <view class="dots">
        <view v-for="(item, index) in bannerList" :key="index" :class="['dot', { active: index === current }]"></view>
      </view>
    </view>

    <!-- equipment_list -->
    <view class="equipment_list">
      <!-- equipment_option-->
      <view class="equipment_option flex align-center" @tap="pickerCfg.open">
        <view class="equipment_option_title">
          <uv-text align="center" bold :text="selectedActiveCode.stationName" :lines="1"></uv-text>
        </view>
        <uv-icon class="ml-2" name="arrow-down"></uv-icon>
      </view>

      <!-- equipment -->
      <view class="equipment_list_view">
        <view class="equipment_list_view_content">
          <view class="equipment_list_view_title">今日总车次</view>
          <view class="equipment_list_view_number" :style="{ color: 'rgba(24, 144, 255, 1)' }">{{ summary.todayCarCount
            }}
          </view>
        </view>
        <view class="equipment_list_view_content">
          <view class="equipment_list_view_title">今日总净重</view>
          <view class="equipment_list_view_number" :style="{ color: 'rgba(255, 141, 26, 1)' }">{{ summary.todayTotalJz
            }}
          </view>
        </view>
        <view class="equipment_list_view_content">
          <view class="equipment_list_view_title">待审核车辆</view>
          <view class="equipment_list_view_number" :style="{ color: 'rgba(165, 214, 63, 1)' }">
            {{ appointSummary.appointCarCount }}
          </view>
        </view>
        <view class="equipment_list_view_content">
          <view class="equipment_list_view_title">本月总车次</view>
          <view class="equipment_list_view_number" :style="{ color: 'rgba(24, 144, 255, 1)' }">{{ summary.monthCarCount
            }}
          </view>
        </view>
        <view class="equipment_list_view_content">
          <view class="equipment_list_view_title">本月总净重</view>
          <view class="equipment_list_view_number" :style="{ color: 'rgba(255, 141, 26, 1)' }">{{ summary.monthTotalJz
            }}
          </view>
        </view>
        <view class="equipment_list_view_content">
          <view class="equipment_list_view_title">本月异常数据</view>
          <view class="equipment_list_view_number" :style="{ color: '#000' }">0</view>
        </view>
      </view>
    </view>

    <!-- order_notice-->
    <view class="order_notice_list">

      <view class="order_notice_title">预约通知</view>

      <TabListComponents :items="appointSummary.list" @detail="toDetail"></TabListComponents>

    </view>

  </view>
  <uv-picker ref="picker" :defaultIndex="pickerCfg.defaultIndex" keyName="stationName" round="12"
    :columns="pickerCfg.source" @confirm="pickerCfg.confirm" @cancel="pickerCfg.cancel"></uv-picker>
</template>
<script setup lang="ts">

import { onShow, onReachBottom, onLoad } from '@dcloudio/uni-app'
import { ref, reactive, toRaw, unref, nextTick } from 'vue'
import { useMemberStore, useTenantSystemStore, usePoundStore } from '@/stores'
import { getMemberProfileAPI } from '@/services/profile'
import { mobileClientSummary } from '@/services/report'
import { latestActiveCodeWithCustomLoginInfo } from '@/services/active-code'
import { themeColor } from '@/utils/index';
import { TableNameEnum, CURDOperationEnum } from '@/enums/tableCurdEnum'
import mqttStatus, { on as mqttOn, MQTTEvent, connect, getPoundFields, tableCurd, getMainApplication } from '@/utils/mqtt';
import TabListComponents from '@/components/tab-list-components/index.vue'

const memberStore = useMemberStore()
const systemStore = useTenantSystemStore()
const poundStore = usePoundStore()

const customerLoginInfo = ref({
  companyName: '--',
  companyWebsite: '',
  servicePhone: '--',
  loginBGImage: ''
})

const summary = ref({
  todayCarCount: 0,
  todayTotalJz: 0,
  monthCarCount: 0,
  monthTotalJz: 0,

})

const appointSummary = ref({
  appointCarCount: 0,
  list: []
})

// const listLoading = ref('loading')
// const loading = ref(true)

const status = ref(0)
// const orderNoticeListView = [
//   {
//     carNumber: '粤A12345',
//     orderTimer: '22024-01-01 11:11:11',
//     customer: '深圳双髻鲨',
//     goods: '水泥',
//     other: '其他',
//     status: status,
//     statusName: status.value == 0 ? '已审核' : '未通过',
//     btnColor: status.value == 0 ? 'rgba(26, 102, 255, 1)' : 'rgba(249, 164, 212, 1)',
//   }, {
//     carNumber: '粤A12345',
//     orderTimer: '22024-01-01 11:11:11',
//     customer: '深圳双髻鲨',
//     goods: '水泥',
//     other: '其他',
//     status: 1,
//     statusName: '未审核',
//     btnColor: 'rgba(249, 164, 212, 1)',
//   }
// ]
/// banner
const bannerList = ([
  // 这里填充你的banner图片链接
  { image: '@/static/images/login-bg.png' },
  { image: '@/static/images/login-bg.png' },
  { image: '@/static/images/login-bg.png' }
])
const current = ref(0)
const autoplay = ref(false)
const interval = ref(5000)
const duration = ref(500)


const searchForm = reactive({
  page: 1,
  limit: 10,
})

let dynamicSearch = {}

const pagedRecordList = reactive({
  hasNextPage: true,
  totalItemCount: 0,
  rows: []
})

const picker = ref()
const pickerCfg = reactive({
  source: [],
  defaultIndex: [0],
  confirm: ({ value }) => {
    selectedActiveCode.hardwareCode = value[0].hardwareCode
    selectedActiveCode.stationName = value[0].stationName
    onActiveCodeChangeHandle(selectedActiveCode.hardwareCode)
  },
  open: () => {
    picker.value.open()
  },
  cancel: () => {
    picker.value.close()
  }
})

const selectedActiveCode = reactive({
  hardwareCode: '',
  stationName: '未选择'
})

// const tabs = reactive([{
//   type: 'all',
//   name: '全部',
//   index: 0,
//   searchHandle: () => {
//     dynamicSearch = { By20: false }
//   }
// }, {
//   type: '0',
//   name: '未完成',
//   index: 1,
//   searchHandle: () => {
//     dynamicSearch = {
//       By20: false
//     }
//   }
// }, {

//   name: '已完成',
//   index: 2,
//   searchHandle: () => {
//     dynamicSearch = {
//       By20: false
//     }
//   }
// }, {
//   type: '2',
//   name: '已作废',
//   index: 3,
//   searchHandle: () => {
//     dynamicSearch = {
//       Valid: 0,
//       By20: false
//     }
//   }
// }, {
//   type: '3',
//   name: '已修改',
//   index: 4,
//   searchHandle: () => {
//     dynamicSearch = {
//       By20: true
//     }
//   }
// }])

// const curTab = ref(0)

// 页面加载
onShow(() => {
  if (memberStore.profile && pickerCfg.source.length == 0) {
    getMemberProfileAPI(null).then(data => {
      if (data.activeCodes.length && !selectedActiveCode.hardwareCode) {
        const code = data.activeCodes[0]
        selectedActiveCode.hardwareCode = code.hardwareCode
        selectedActiveCode.stationName = code.stationName
        pickerCfg.source = [[...data.activeCodes]]
        data.selectedActiveCode = code.hardwareCode
      }
      memberStore.setDetailProfile(data)
      onActiveCodeChangeHandle(data.selectedActiveCode)
    }).catch(() => { })
  }

})

const callPhone = () => {
  if (customerLoginInfo.value.servicePhone) {
    uni.makePhoneCall({
      phoneNumber: customerLoginInfo.value.servicePhone
    })
  }
}

const toDetail = (item) => {
  uni.navigateTo({
    url: `/pagesAppointment/detail?id=${item.id}`,
    events: {
      'updated': () => {
        getSummary()
        getAppointSummary()
      }
    },
    success: ({ eventChannel }) => {
      eventChannel.emit('init', { ...toRaw(unref(item)) })
    },
  })
}

const onMQTTConnected = () => {
  // getPoundFields(null, ({ Success, Message, Body }) => {
  //   if (!Success) {
  //     uni.showModal({
  //       title: '错误',
  //       content: `获取磅单字段失败:${Message}`,
  //       showCancel: false,
  //     })
  //     return;
  //   }
  //   const { fields } = Body;
  //   poundStore.setFields(fields)

  // })

  latestActiveCodeWithCustomLoginInfo(mqttStatus.code).then(data => {
    customerLoginInfo.value = data
  }).catch(() => {

  })
  getSummary()
  getAppointSummary()
}

onLoad(() => {
  mqttOn(MQTTEvent.Connect, onMQTTConnected)
})

onReachBottom(() => {
  if (!pagedRecordList.hasNextPage) {
    return
  }
  searchForm.page++
  getAppointSummary()
})

const onActiveCodeChangeHandle = (code: string) => {
  // 连接mqtt获取动态列
  getMainApplication(code)
    .then((data) => {
      if (!data) {
        uni.showModal({
          title: '错误',
          content: '站点主程序未上线或已断开',
          showCancel: false,
        })
        return;
      }
      mqttStatus.appOnline = data.online;
      if (mqttStatus.code == data.code) {
        return;
      }
      mqttStatus.code = data.code;
      if (!mqttStatus.online) {
        connect(data);
      } else {
        onMQTTConnected();
      }
    })
    .catch(() => { })
    .finally(() => { });

}


// const processList = ({ Success, Message, Body }) => {
//   if (!Success) {

//     uni.showModal({
//       title: '错误',
//       content: `获取数据失败:${Message}`,
//       showCancel: false,
//     })

//   } else {
//     const { rows, hasNextPage } = Body
//     listLoading.value = hasNextPage ? 'loadmore' : 'nomore'
//     pagedRecordList.hasNextPage = hasNextPage
//     if (searchForm.page == 1) {
//       pagedRecordList.rows = rows
//     } else {
//       pagedRecordList.rows = [...pagedRecordList.rows, ...rows]
//     }

//   }

//   setTimeout(() => {
//     loading.value = false
//   }, 1000)
//   uni.stopPullDownRefresh()
// }

const getAppointSummary = () => {
  // listLoading.value = 'loading'
  appointSummary.value.list = []
  mobileClientSummary(mqttStatus.code).then(data => {
    appointSummary.value = data
  }).catch(() => { }).finally(() => {

  })
}

const getSummary = () => {
  tableCurd({
    tableName: TableNameEnum.WeighingRecord,
    operation: CURDOperationEnum.Summary,
    body: {
      ...searchForm,
      ...dynamicSearch
    }
  }, ({ Success, Message, Body }) => {
    summary.value = Body
  })


}

// const onTabChange = ({ index, searchHandle }) => {
//   searchForm.limit = 10
//   curTab.value = index
//   searchForm.page = 1
//   searchHandle()
//   getList()
// }


</script>

<style lang="scss">
.top_banner {
  background-image: url('../../static/images/index/index_banner_bg.png');
  background-size: cover;
  border-radius: 14px;
  color: white;
  padding: 25px 32px;
  margin: 28px;

  .top_banner_title {
    font-size: 18px;
    font-weight: 500;
  }

  .top_banner_dec {
    font-size: 14px;
    font-weight: 300;
  }

  .top_banner_tel {
    font-size: 14px;
    font-weight: 700;
    color: rgba(81, 105, 240, 1);
    background-color: white;
    border-radius: 50px;
    display: inline-block;
    padding: 5px 20px;
    margin-top: 20px;
  }
}

.equipment_list {
  margin: 20px;

  .equipment_option {
    display: flex;
    flex: 1;

    .equipment_option_icon {
      width: 20;
      height: 20;
    }

    .equipment_option_title {
      margin-left: 10px;
    }
  }

  .equipment_list_view {
    display: grid;
    grid-template-columns: repeat(3, 2fr);
    margin: 5px 10px;
    border-radius: 10px;
    overflow: hidden;
    box-shadow: 5px 5px 25px rgba(0, 0, 0, 0.1);

    .equipment_list_view_content {
      color: rgba(166, 166, 166, 1);
      background-color: white;
      font-size: 12px;
      font-weight: 400;
      height: 50px;
      margin: 1px;
      overflow-x: auto;
      overflow-y: hidden;
      display: flex;
      flex-direction: column;
      flex: 0 0 auto;
      justify-content: center;
      align-items: center;

      .equipment_list_view_title {}

      .equipment_list_view_number {}
    }
  }

}

.order_notice_list {
  .order_notice_title {
    font-weight: 600;
    margin-left: 10px;
  }

  .order_notice_list_view {
    font-size: 12px;

    .order_notice_content {
      border-radius: 10px;
      background-color: white;
      padding: 5px 10px;
      margin: 10px 10px 15px 10px;

      .order_notice_order_timer {
        color: gray;
      }

      .order_notice_sub_content {
        display: flex;
        color: gray;
        justify-content: space-between;

        .order_notice_sub_content_dec {
          display: flex;
        }

        .order_notice_status {
          border: 1px solid blue;
          border-radius: 10px;
          padding: 3px 15px;
        }
      }
    }
  }
}

.banner-container {
  position: relative;
  height: 180px;
}

.slide-image {
  width: 100%;
  height: 300rpx;
}

.dots {
  display: flex;
  justify-content: center;
  position: absolute;
  bottom: 10px;
  width: 100%;
}

.dot {
  width: 10rpx;
  height: 10rpx;
  border-radius: 50%;
  background-color: #fff;
  margin: 0 5rpx;
  opacity: 0.5;
  transition: opacity 0.3s;
}

.dot.active {
  opacity: 1;
  width: 30rpx;
  background-color: white;
  border-radius: 10rpx;
}

.uv-navbar {
  ::v-deep .uv-navbar__content {
    background-color: #F5F5F5;
    // background-image: url('@/static/images/login-bg.png') !important;
    background-repeat: no-repeat;
    background-position: top;
    background-size: 100% 45%;
    background-attachment: fixed;

  }

}

.uv-tabs {
  // background-image: url('@/static/images/login-bg.png') !important;
  background-repeat: no-repeat;
  background-position: top;
  background-size: 100% 45%;
  background-attachment: fixed;

}

.pound-item {
  border-radius: 20rpx;
  position: relative;
}

.code-tag {
  border-radius: 12rpx;
}

.status {
  position: absolute;

  right: -10rpx;
  top: -20rpx;

  .tag {
    position: relative;

    .img {
      position: absolute;
      right: 0rpx;
      top: 0rpx;
    }

    .txt {
      position: absolute;
      right: 46rpx;
      top: 6rpx;
      min-width: 100rpx;
    }
  }
}
</style>
